package com.example.backend.service;

import com.example.backend.mapper.GoodsMapper;
import com.example.backend.model.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
public class GoodsService {
    // remember to add @Transactional when you need to commit
    @Autowired
    GoodsMapper mapper;

    public Goods findOne(Integer id) {
        Optional<Goods> matchGoods = Optional.ofNullable(mapper.findOne(id));
        try {
            if(matchGoods.isPresent()) {
                matchGoods.get().loadImage();
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }

        return matchGoods.orElse(null);
    }

    public List<Goods> findWith(Map<String, String> params) {
        List<Goods> matchList = null;
        if(params == null) {
            matchList = mapper.findAll();
        } else {
            matchList = mapper.findWith(params);
        }

        try {
            for(Goods goods: matchList) {
                goods.loadImage();
            }

            return matchList;
        } catch (IOException exception) {
            exception.printStackTrace();
            return Collections.emptyList();
        }
    }

    @Transactional
    public int updateOne(Goods goods) {
        return mapper.updateOne(goods);
    }

    @Transactional
    public int insertOne(Goods goods) {
        return mapper.insertOne(goods);
    }

    @Transactional
    public int deleteOne(int id) {
        return mapper.deleteOne(id);
    }
}
